package myky.com.doctorapp.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import myky.com.doctorapp.R;
import myky.com.doctorapp.entity.LoginEntity;
import myky.com.doctorapp.entity.LoginSuccessEntity;
import myky.com.doctorapp.entity.SmsCodeEntity;
import myky.com.doctorapp.base.BaseActivity;
import myky.com.doctorapp.base.BaseFragment;
import myky.com.doctorapp.contract.PnLoginFragmentContract;
import myky.com.doctorapp.presenter.PnLoginFragmentPresenter;
import myky.com.doctorapp.utils.CheckTextUtils;
import myky.com.doctorapp.utils.Constants;
import myky.com.doctorapp.utils.CountDownTimerUtils;
import myky.com.doctorapp.utils.ErrorCodeUtils;
import myky.com.doctorapp.utils.ShareUtil;
import myky.com.doctorapp.utils.SpanUtils;
import myky.com.doctorapp.utils.ThreadUtil;
import myky.com.doctorapp.utils.ToastUtils;
import myky.com.doctorapp.wight.AddAndSubEditText;
import myky.com.doctorapp.wight.SelfDialog;

/**
 * @author Mr.li
 */

public class PnLoginFragment extends BaseFragment<PnLoginFragmentPresenter, LoginEntity.PayLoadBean> implements PnLoginFragmentContract.View {
    @BindView(R.id.activity_phone_mobile_et)
    AddAndSubEditText mActivityPhoneMobileEt;
    @BindView(R.id.activity_phone_sms)
    Button mActivityPhoneSms;
    @BindView(R.id.activity_phone_number_et)
    AddAndSubEditText mActivityPhoneNumberEt;
    @BindView(R.id.privacy_policy_tv)
    TextView mPrivacyPolicyTv;
    @BindView(R.id.login_phoneNumber)
    LinearLayout mLoginPhoneNumber;
    @BindView(R.id.activity_login_button)
    Button mActivityLoginButton;

    private String user_phone;
    private int smsKey;
    private String smsCode;
    private int SMSCODELENGTH = 4;
    private Context mContext;

    @Override
    protected int injectTarget() {
        return 0;
    }

    @Override
    protected void doRetry() {

    }

    @Override
    public PnLoginFragmentPresenter getPresenter() {
        return new PnLoginFragmentPresenter();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fra_pnlogin;
    }

    @Override
    protected void initView() {
        mContext = getActivity();
        setBtnColor(mActivityPhoneMobileEt, mActivityPhoneSms);
        BaseActivity.setPNSpace(mActivityPhoneMobileEt);
        SpanUtils spanUtils = new SpanUtils();
        spanUtils.append(getResources().getString(R.string.login_agreement))
                .append("《C麦隐私政策》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        //跳转隐私政策
//                        Intent intent = new Intent(mContext, WebProtocolActivity.class);
//                        intent.putExtra("URL", UrlUtils.USER_SECREAT_URL);
//                        intent.putExtra("TITLE_H5", "C麦隐私政策");
//                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        ds.setColor(getResources().getColor(R.color.theme_app));
                        ds.setUnderlineText(false);
                    }
                }).append(" 《C麦用户协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        //跳转用户协议
//                        Intent intent = new Intent(mContext, WebProtocolActivity.class);
//                        intent.putExtra("URL", UrlUtils.USER_SERVICE_URL);
//                        intent.putExtra("TITLE_H5", "C麦用户协议");
//                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        ds.setColor(getResources().getColor(R.color.theme_app));
                        ds.setUnderlineText(false);
                    }
                });
        mPrivacyPolicyTv.setMovementMethod(LinkMovementMethod.getInstance());
        mPrivacyPolicyTv.setText(spanUtils.create());
        AddAndSubEditText.textChangeListener textChangeListener = new AddAndSubEditText.textChangeListener(mActivityLoginButton);
        //监听输入不为空
        textChangeListener.addAllEditText(mActivityPhoneMobileEt, mActivityPhoneNumberEt);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        //mPresenter.quickLogin();
    }

    @Override
    public void showDataError(String errorMessage) {
        SelfDialog.dismissdialog();
        ToastUtils.showAtCenter(errorMessage);
    }

    @Override
    public void showDataSuccess(LoginEntity.PayLoadBean datas) {

    }

    @Override
    public void loginSuccess(LoginSuccessEntity.PayLoadBean infoBean) {
        SelfDialog.dismissdialog();
        ToastUtils.showAtCenter("登录成功");
        Intent intent = new Intent();
        intent.putExtra("IS_LOGIN", "IS_LOGIN");
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    @Override
    public void showCode(SmsCodeEntity.PayloadBean codeEntity) {
        if (codeEntity.getId() != null) {
            smsKey = codeEntity.getId();
            ThreadUtil.runInUIThread(getActivity(), new Runnable() {
                @Override
                public void run() {
                    CountDownTimerUtils downTimerUtils = new CountDownTimerUtils(mActivityPhoneSms, 60000, 1000);
                    downTimerUtils.start();//倒计时
                }
            });
        } else {
            String errorInfo = ErrorCodeUtils.getErrorMsg(codeEntity.getErrorCode().getSendsmserror());
            ToastUtils.show(errorInfo);
        }

    }

    @Override
    public void getCodeError(int errorCode) {
        if (errorCode != -1) {
            switch (errorCode) {
                case 1015:
                    ToastUtils.show("获取验证码太频繁，请1分钟后再试");
                    break;
                case 1009:
                    ToastUtils.show("获取验证码太频繁，请1小时后再试");
                    break;
                default:
                    try {
                        String errorInfo = ErrorCodeUtils.getErrorMsg(errorCode);
                        ToastUtils.show(errorInfo);
                    } catch (Exception e) {
                        ToastUtils.show("服务异常，请稍后再试或联系客服");
                    }
                    break;
            }
        } else {
            ToastUtils.show("服务异常，请稍后再试或联系客服");
        }
        ToastUtils.showAtCenter(String.valueOf(errorCode));
    }

    @OnClick({R.id.activity_phone_sms, R.id.activity_login_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_phone_sms:
                user_phone = mActivityPhoneMobileEt.getText().toString().replaceAll(" ", "");
                if (CheckTextUtils.isMobileNumber(user_phone)) {
                    mPresenter.getSmsCode(user_phone, "quickLogin");
                } else {
                    ToastUtils.showAtCenter("手机号码格式不正确");
                }
                break;
            case R.id.activity_login_button:
                user_phone = mActivityPhoneMobileEt.getText().toString().replaceAll(" ", "");
                smsCode = mActivityPhoneNumberEt.getText().toString();
                if (CheckTextUtils.isMobileNumber(user_phone)) {
                    if (smsKey == 0 || smsCode.length() < SMSCODELENGTH) {
                        ToastUtils.showAtCenter("手机验证码不正确");
                    } else {
                        ShareUtil.putData(Constants.USERPHONE, user_phone);
                        ShareUtil.putData(Constants.SMSKEY, smsKey);
                        ShareUtil.putData(Constants.SMSCODE, smsCode);
                        SelfDialog.progressdialog(getActivity(), "登录中...");
                        ShareUtil.putData("isQuickLogin", true);
                        mPresenter.quickLogin();
                    }
                } else {
                    ToastUtils.showAtCenter("手机号码格式不正确");
                }
                break;
            default:
        }
    }
}